#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:zhuyan
@file: csvutil.py
@time: 2018/08/28
"""
import csv
from file.log import Log


class CsvUtil:

    def __init__(self):
        """
        1. 将csv数据读取出来并转化成list(dict)格式
        2. 将list(dict)数据写入csv文件，第一行为表头
        3. 编码格式读写均固定为gbk，方便windows下查看。
        """
        self.log = Log()

    def read(self, file_path):
        """
        :param file_path:
        :return:
        """
        with open(file_path, newline='', encoding='gbk') as csvfile:
            reader = csv.DictReader(csvfile)
            list_dict_data = []
            for row in reader:
                list_dict_data.append(row)
        if len(list_dict_data) > 0:
            self.log.info("从csv:%s读取到的数据为：%s", file_path, list_dict_data)
        else:
            self.log.info("从csv:%s读取到的数据为空", file_path)
        return list_dict_data

    def write(self, list_dict_data, file_path):
        """
        写入csv文件，编码格式gbk。因dict原因写入的字段无序。
        1. 如果没有文件，则创建。如果有，则覆盖。
        2. 写入文件Header
        3. 写入文件内容
        :param list_dict_data:[{"":"","":""},{}]
        :param file_path:
        :return:
        """
        self.log.info("开始写入csv文件，文件路径，文件内容:%s")
        if list_dict_data is not None and len(list_dict_data) > 0:
            keys = list_dict_data[0].keys()
        else:
            self.log.error("list_dict_data为空:%s", str(list_dict_data))
            return None

        with open(file_path, "w+", encoding='gbk', newline="") as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=keys)
            writer.writeheader()
            writer.writerows(list_dict_data)


if __name__ == '__main__':
    csvUtil = CsvUtil()
    list_dict = [{u"姓名": u"燕子", u"年龄": 5}, {u"姓名": u"太阳", u"年龄": 3}, {u"姓名": u"石头", u"年龄": 6}]
    # csvUtil.write_demo(list_dict_data=list_dict, file_path="a.csv")
    print(csvUtil.read("a.csv"))
